<?php

namespace App\Http\Controllers;

use App\Services\OSS;
use App\Traits\ApiResponse;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Intervention\Image\Facades\Image;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    use ApiResponse;
    /**
     * 上传oss
     */
    protected function upload($file, $action = '')
    {

        if ($file->isValid()) {
            $content_type = mime_content_type($file->getRealPath());

            $file_name = date('Y-m-d').'/' . uniqid() . '.' . $file->extension();

            $content = Image::make($file)->encode()->encoded;

            $bucket_name = config('oss.bucketName');

            OSS::publicUploadContent($bucket_name, $file_name, $content,['ContentType' => $content_type]);//设置HTTP头

            //获取公开文件URL
            $url = OSS::getPublicObjectURL($bucket_name, $file_name);
            //获取私密文件URL
            return compact('url');
        } else {
            throw new ApiException('文件上传失败', 500);
        }
    }
}
